#include "imagewidget.h"
#include <QtGui>
#include <cv.h>

ImageWidget::ImageWidget(QWidget *parent) :
    QWidget(parent)
{
    img = NULL;
    qImg = NULL;

}

ImageWidget::~ImageWidget()
{
    if( img )
    {
        cvReleaseImage(&img);
    }

    if( qImg )
    {
        delete qImg;
    }
}

void ImageWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    if( qImg )
    {
        painter.drawImage(QPoint(0,0),*qImg);
    }
    else
    {
        painter.fillRect(0,0,width(),height(),Qt::SolidPattern);
    }
}

QSize ImageWidget::sizeHint() const
{
    if( qImg )
    {
        return qImg->size();
    }
    else
    {
        return QSize(300,300);
    }
}

void ImageWidget::onUpdateImage(const IplImage *frame)
{

    if( img==NULL )
    {
        qImg = new QImage(QSize(frame->width,frame->height),QImage::Format_RGB888);

        img = cvCreateImageHeader(cvSize(frame->width,frame->height),IPL_DEPTH_8U,3);
        img->imageData = (char *)qImg->bits();

        emit updateSize(img);

    }

    if( img->width!=frame->width || img->height!=frame->height )
    {
        cvReleaseImage(&img);
        delete qImg;

        qImg = new QImage(QSize(frame->width,frame->height),QImage::Format_RGB888);

        img = cvCreateImageHeader(cvSize(frame->width,frame->height),IPL_DEPTH_8U,3);
        img->imageData = (char *)qImg->bits();

        emit updateSize(img);

    }

    if( frame->origin == IPL_ORIGIN_TL )
    {
        cvCopy(frame,img,0);
    }
    else
    {
        cvFlip(frame,img,0);
    }

    cvCvtColor(img,img,CV_BGR2RGB);
    update();

}

IplImage *ImageWidget::getCurrentImage()
{
    if( img )
    {
        IplImage *currentImg = cvCreateImage(cvSize(img->width,img->height),IPL_DEPTH_8U,3);
        cvCvtColor(img,currentImg,CV_RGB2BGR);
        return currentImg;
    }
    else
    {
        return NULL;
    }
}


